<template>
  <canvas ref="canvas" class="fit overflow-hidden" @dblclick="handleHighlight"></canvas>
  <q-resize-observer @resize="onResize"></q-resize-observer>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from 'vue'
import * as THREE from 'three'
import { MapControls } from 'three/addons'
import { MapUtils, initLights } from './MapGlobal/MapUtils'
import { CameraUtils } from './MapGlobal/CameraUtils'
import { mapDataGzip } from './MapGlobal/data_3d'
import { unzip } from 'src/utils/PakoJson'
import { handleMap3dData } from './MapGlobal/utils'

// 解析地图数据
const mapData = JSON.parse(unzip(mapDataGzip.data.baseMapDataGzip))
const mapInfo = handleMap3dData(mapData)

// 组件引用和状态
const canvas = ref(null)
const screenSize = ref({ width: 0, height: 0 })

// Three.js核心对象
let scene = null, camera = null, renderer = null, controls = null
let mapDrawer = null, cameraController = null

const initCanvas = () => {
  scene = new THREE.Scene()
  // 初始化渲染器
  renderer = new THREE.WebGLRenderer({
    canvas: canvas.value,
    antialias: true,
    alpha: true
  })
  renderer.setSize(screenSize.value.width, screenSize.value.height)
  renderer.setPixelRatio(window.devicePixelRatio)
  renderer.setAnimationLoop(animate)

  // 初始化相机（fov为初始值，后续会被动态调整）
  camera = new THREE.PerspectiveCamera(
    40, // 初始fov（会被adjustFovByDistance优化）
    screenSize.value.width / screenSize.value.height,
    0.1,
    1000
  )

  // 初始化控制器
  controls = new MapControls(camera, renderer.domElement)
  controls.enableDamping = true
  controls.dampingFactor = 0.05
  controls.screenSpacePanning = false
  controls.maxPolarAngle = Math.PI / 2
  controls.zoomToCursor = true

  // 初始化灯光
  initLights(scene)

  // 初始化地图工具
  mapDrawer = new MapUtils(scene, camera, renderer)
  cameraController = new CameraUtils(camera, controls)

  // 关键：调用新方法实现地图最大化适配
  // 可调整padding（如0.05=5%边距，0=无空白）
  mapDrawer.drawMap(mapInfo)
  cameraController.fitMapToViewMaximize(mapInfo, 0.05)
  const size = {
    width: 1700,
    height: 851
  }
  onResize(size)
}

const handleHighlight = e => {
  console.log(e, '++++')
}

const animate = () => {
  controls.update()
  renderer.render(scene, camera)
}

const onResize = (size) => {
  screenSize.value = size
  if (!camera || !renderer) return
  cameraController.handleResize(size)
  renderer.setSize(size.width, size.height)
  // 可选：窗口 resize 后重新最大化（确保适配新视口）
  // cameraController.fitMapToViewMaximize(mapInfo, 0.05)
}

// 组件生命周期
onMounted(initCanvas)
onUnmounted(() => {
  if (renderer) {
    renderer.setAnimationLoop(null)
  }
  if (mapDrawer) {
    mapDrawer.clearMap()
  }
})
</script>